#!/usr/bin/env bash
set -euo pipefail

# 参数：
# 1) flag (如: Chord_test_CRL_0.1.3_)
# 2) apkPathOrDir (APK 文件路径或目录)
# 3) ver_desc 可选，变更日志（默认等于 flag）
# 4) downloadUrl 可选，下载前缀 URL（用于钉钉通知）

flag="${1:-}"
apkArg="${2:-}"
changeLog="${3:-}"
downloadUrl="${4:-}"

if [[ -z "$flag" || -z "$apkArg" ]]; then
  echo "Usage: $0 <flag> <apkPathOrDir> [ver_desc] [downloadUrl]" >&2
  echo "Example (dir): $0 Chord_test_CRL_0.1.3_ C:/mateurp_pipline/mate-client-adnroid/app/build/outputs/apk/Release" >&2
  echo "Example (file): $0 Chord_test_CRL_0.1.3_ C:/path/to/your.apk" >&2
  echo "Example (with desc): $0 Chord_test_CRL_0.1.3_ C:/path/to/your.apk \"Fix crash\"" >&2
  exit 1
fi

if [[ -z "${changeLog:-}" ]]; then
  changeLog="$flag"
fi

# 生成时间戳
timestamp="$(date +%Y%m%d%H%M)"

# 解析 APK 源与目标目录
sourceApk=""
destDir=""

# 大小写不敏感地检测 .apk 扩展
shopt -s nocasematch || true
if [[ -f "$apkArg" && "$apkArg" == *.apk ]]; then
  sourceApk="$apkArg"
  destDir="$(cd "$(dirname "$apkArg")" && pwd)"
fi

# 若未解析到文件，则当作目录，从目录中挑选最新 APK
if [[ -z "$sourceApk" ]]; then
  if [[ ! -d "$apkArg" ]]; then
    echo "Path not found: $apkArg" >&2
    exit 1
  fi
  apkDir="$apkArg"
  latestApk=""
  if command -v find >/dev/null 2>&1; then
    latestApk=$(find "$apkDir" -type f -name "*.apk" -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -n1 | cut -d' ' -f2- || true)
  fi
  if [[ -z "$latestApk" ]]; then
    latestApk=$(ls -t "$apkDir"/*.apk 2>/dev/null | head -n1 || true)
  fi
  if [[ -z "$latestApk" || ! -f "$latestApk" ]]; then
    echo "No APK found in directory: $apkDir" >&2
    exit 1
  fi
  sourceApk="$latestApk"
  destDir="$apkDir"
fi

destApkName="${flag}${timestamp}.apk"
destApkPath="${destDir%/}/${destApkName}"
cp -f "$sourceApk" "$destApkPath"

echo "APK copied and renamed: $destApkPath"

# 上传 APK 至应用商店（按 .bat 脚本保持为模拟上传）
uploadUrl="http://appstore-admin.etouch.cn/app-store-server/api/app/pkg/latest/upload"
respFile="${destDir%/}/upload_resp_${timestamp}.txt"
echo "Uploading to: $uploadUrl"
# 如需真实上传，请取消注释下方并删除 echo
curl -sSL -X POST "$uploadUrl" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@${destApkPath}" \
  -F "ver_desc=${changeLog}" > "$respFile" 2>&1
printf '"%s" "%s"\n' "$destApkPath" "$changeLog" > "$respFile" 2>&1

echo "Server response saved to: $respFile"

# 钉钉通知
dingUrl="https://oapi.dingtalk.com/robot/send?access_token=1dd9ef311951334ba9e001f194f78c99ee8b74fff2c56b5f899c1727302f60b8"
dingBody="${destDir%/}/dingtalk_${timestamp}.json"
dingResp="${destDir%/}/dingtalk_resp_${timestamp}.txt"
printf '{"msgtype":"text","text":{"content":"安卓打包上传：%s%s"}}' "${downloadUrl:-}" "$destApkName" > "$dingBody"
curl --ssl-no-revoke -s -H "Content-Type: application/json" -X POST --data "@${dingBody}" "$dingUrl" > "$dingResp" 2>&1 || true

echo "END Upload APK"
exit 0